package com.kgar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kgar.dao.UserDao;
import com.kgar.dto.Result;
import com.kgar.dto.UserDTO;
import com.kgar.entity.pojo.User;
import com.kgar.service.LoginService;
import com.kgar.service.ResumeService;
import com.kgar.service.UserService;
import com.kgar.util.RegexUtils;
import com.kgar.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.kgar.util.RedisConstants.CACHE_USERINFO_KEY;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Resource
    private ResumeService resumeService;

    @Resource
    @Lazy
    private LoginService loginService;

    @Override
    public Result queryById() {
        Integer userId = UserHolder.getUser().getUserId();
        //先从redis查询
        Map<Object, Object> map = redisTemplate.opsForHash().entries(CACHE_USERINFO_KEY + userId);
        User user = BeanUtil.toBean(map, User.class);
        if (!BeanUtil.isEmpty(user)) {
            return Result.ok(user);
        }
        //再从数据库查
        user = getById(userId);
        Map<String, Object> userMap = null;
        if (user != null) {
            userMap = BeanUtil.beanToMap(user, new HashMap<>(),
                    CopyOptions.create()
                            .setFieldValueEditor((fieldName, fieldValue) ->
                                    Objects.requireNonNullElse(fieldValue, "")));
            redisTemplate.opsForHash().putAll(CACHE_USERINFO_KEY + userId, userMap);
        }
        return user != null ? Result.ok(userMap) : Result.fail("用户不存在！");
    }

    @Override
    public Result deleteById() {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getUserId();
        boolean b = removeById(userId);
        if (b) {
            loginService.removeById(userId);
            HashMap<String, Object> map = new HashMap<>();
            map.put("user_id",userId);
            resumeService.removeByMap(map);
            b = Boolean.TRUE.equals(redisTemplate.delete(CACHE_USERINFO_KEY + userId));
        }
        if (b) {
            log.info(user.getUserName() + "用户成功注销");
        } else {
            log.info(user.getUserName() + "用户注销失败");
        }
        return b ? Result.ok() : Result.fail("注销失败！");
    }

    @Override
    public Result saveUserInfo(User user) {
        if(RegexUtils.isEmailInvalid(user.getEmail()))
            return Result.fail("邮箱格式不正确");
        UserDTO user1 = UserHolder.getUser();
        Integer userId = user1.getUserId();
        user.setUserId(userId);

        //先保存数据库
        boolean save = saveOrUpdate(user);
        if (save) {
            //数据库保存成功，再删除redis
            redisTemplate.delete(CACHE_USERINFO_KEY + userId);
        }
        return save ? Result.ok() : Result.fail("保存失败！");
    }

    @Override
    public Result updateUser(User user) {
        UserDTO user1 = UserHolder.getUser();
        Integer userId = user1.getUserId();
        user.setUserId(userId);
        //更新数据库
        boolean b = updateById(user);
        if (b) {
            redisTemplate.delete(CACHE_USERINFO_KEY + userId);
        }
        return b ? Result.ok() : Result.fail("更新失败！");
    }
}
